package com.test.demos.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import com.test.demos.mapper.PermissionMapper;
import com.test.demos.mapper.RoleMapper;
import com.test.demos.mapper.RolePermissionMapper;
import com.test.demos.mapper.UserRoleMapper;
import com.test.demos.pojo.dto.RegisterDTO;
import com.test.demos.pojo.entity.UserRole;
import com.test.demos.pojo.entity.Users;
import com.test.demos.mapper.UsersMapper;
import com.test.demos.pojo.vo.UserLoginVO;
import com.test.demos.pojo.vo.UserVO;
import com.test.demos.service.UsersService;
import com.test.demos.utils.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.test.demos.Constant.USER;


@Slf4j
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private  UsersMapper usersMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public UserLoginVO login(String username, String password) {
        // 第一步：校验账号密码是否正确
        if (username == null || password == null) {
           throw new RuntimeException("账号或密码不能为空");
        }
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(Users::getUsername).eq(username)
                .and(Users::getPassword).eq(password);


        Users user = usersMapper.selectOneByQuery(queryWrapper);
        System.out.println("user = " + user);
        if (user == null) {
           return null;
        }
        // 第二步：根据账号id，进行登录
        StpUtil.login(user.getUserId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 3. 获取用户角色列表
        System.out.println("tokenInfo = " + tokenInfo);
        UserLoginVO vo = new UserLoginVO();
        vo.setUserId(user.getUserId());
        vo.setUsername(user.getUsername());
        vo.setTokenInfo(tokenInfo);
        return vo;
    }

    @Override
    public Result logout() {
        // 当前会话注销登录
        // 获取当前会话是否已经登录，返回true=已登录，false=未登录
        if (StpUtil.isLogin()) {
            StpUtil.logout();
            return Result.ok("退出成功");
        } else {
            return Result.error("退出失败");
        }
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
       String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        String name = registerDTO.getName();
        if (username == null || password == null) {
            return Result.error("账号或密码不能为空");
        }
        System.out.println("username = " + username);
        // 校验账号是否存在
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(Users::getUsername).eq(username);
        Users user = usersMapper.selectOneByQuery(queryWrapper);
        if (user != null) {
            return Result.error("账号已存在");
        }
        // 注册账号
        Users newUser = new Users();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setName(name);
        usersMapper.insert(newUser);
        Integer userId = newUser.getUserId();
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(USER);
        userRoleMapper.insert(userRole);
        return Result.ok("注册成功");
    }

    @Override
    public UserVO getUserInfo() {
        // 获取当前登录的账号id
        Integer userId = StpUtil.getLoginIdAsInt();
        if (userId == null) {
            return null;
        }

        // 查询用户信息，根据用户ID精确查询单个用户
        UserVO userVO = new UserVO();
        usersMapper.selectOneById(userId);
        BeanUtils.copyProperties(usersMapper.selectOneById(userId), userVO);
        List<String> roleList = StpUtil.getRoleList();
        userVO.setRoleList(roleList);
        return userVO;
    }

    @Override
    public Result deleteUser(Integer userId) {
        // 删除用户
        int i = usersMapper.deleteById(userId);
        if (i == 0) {
            return Result.error("删除失败");
        }
        return Result.ok("删除成功");

    }

    @Override
    public List<UserVO> queryAllUsers() {
        List<Users> users = usersMapper.selectAll();
        return users.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());

    }
}


